﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MediaDataModel;
using MediaClient.Common;
using System.Text.RegularExpressions;
using System.Threading;
using FlexCapture;
using System.Diagnostics;
using System.IO;
using MediaClient.Common;
using MediaClient.UserControls;

namespace MediaClient.ImportMedia
{
    public partial class ImportForm : BaseMainForm
    {
        #region private properties

        private int index = 0;

        private int currentY = 32;

        private int splitHeight = 38;

        private FlexEncoder encoder;

        //private string discBarcode = null;

        private string sourceType = "SDI";

        private int codeRate = 25000;
 
        private string mediaPackType = null;

        /// <summary>
        /// 是否在采集中
        /// </summary>
        private bool isRecStart = false;

        private bool isSeeking = false;

        private bool isTaskRuning = false;

        private int iiTdMode = 0;

        private string isTaskDir = "d:\\LocalClips";

        private string isClipsDir = "d:\\LocalClips";

        private string isEncAppFp = @"C:\DBox.Enc\DLEncoder.exe";

        private string isBarcode = "";

        private string isFrameCount = "";

        private Process EncAppproc = null;

        private DataGridViewRow currRecRow;

        private ContextMenuStrip mediaNameColumnMenu = null;

        private string isMSTC = "";

        private int delRowIndex = -1;

        private bool isTaskCue = false;

        private string cueTime = "";

        private bool canStartRec = false;

        private string burnPath = "";

        private Dictionary<string, List<string>> dicMediaPackFile = new Dictionary<string, List<string>>();

        private object burnObjectLock = new object();

        private object burnDiscDriveLock = new object();

        private bool isBurning = false;

        private long burningMediaPackSize = 0;

        private Dictionary<string, DiscState> dicDiscDrive = new Dictionary<string, DiscState>();

        private KeyValuePair<string, long> burningMediaPackInfo = new KeyValuePair<string, long>();

        private ulong discRemainCapacity = 0;

        private ulong secondRemainCapacity = 0;

        private ulong tempCapacity = 0;

        /// <summary>
        /// 高低码率
        /// </summary>
        private string isHFileC = "";

        /// <summary>
        /// Cu计数
        /// </summary>
        int iiTaskCueCount = 0;

        private Dictionary<long, KeyValuePair<string, string>> dicTaskMediaPack = new Dictionary<long, KeyValuePair<string, string>>();
        private List<long> waitingBurnMediaPackList = new List<long>();

        private ImporConfig captureConfig = null;

        private ulong sumTaskMediaPackSize = 0;

        private string markIn = "";

        private string markOut = "";

        /// <summary>
        /// 编码器
        /// </summary>
        public InterEncoder iEnc = new InterEncoder();

        private bool iboolTaskEndMonitor = false;

        private string currentBurnFile = "";

        private string discBarcode = DateTime.Now.ToString("yyyyMMddHHmmss");

        #endregion

        public ImportForm()
        {
            InitializeComponent();
            currentY = pnlMovieName.Location.Y;
            ConnectVTR();
        }

        #region Events

        private void ImportForm_Load(object sender, EventArgs e)
        {
            BurnHelper.RealTimeWriteComplete += burningMediaPack_Complete;
            BurnHelper.RealTimeWriteProcess += burningMediaPack_Process;

            InitializeTimer();
            ImportConfigForm configForm = new ImportConfigForm();
            configForm.ShowDialog();
            this.captureConfig = configForm.CaptureConfig;
            InitializeBurningDiscDrives();
            //GetDiscBarcode();
            this.discRemainCapacity = this.secondRemainCapacity = (ulong)captureConfig.DiscCapacity;
            if (this.captureConfig.BurnType == 1)
                pnlBurnSecond.Visible = false;

            //ConnectVTR();
            
            dgvMediaPack.AutoGenerateColumns = false;
            
            dgvMediaPack.ClearSelection();
            dgvMediaPack.TabStop = false;
            //MessageBox.Show(dgvMediaPack.Rows[0].Cells[1].Value.ToString());
            
            ucVtrCtrMedia.btnMarkIn.Click += new EventHandler(ucVtrCtrMediaMarkIn_Clik);

            //ucVtrCtrMain.btnMarkOut.Click += new EventHandler(btnMarkOut_Click);
            ucVtrCtrMedia.labelEndTD.DoubleClick += new EventHandler(ucVtrCtrMediaMarkOutValue_DoubleClick);
            ucVtrCtrMedia.labelStartTD.DoubleClick += new EventHandler(ucVtrCtrMediaMarkInValue_DoubleClick);
            ucVtrCtrMedia.ReachMarkOut = new UserControls.UCVtrCtr.ReachMarkOutHandler(ucVtrCtrMedia_ReachMarkOut);
            //AddMetaDataControl();

            mediaNameColumnMenu = new System.Windows.Forms.ContextMenuStrip();
            ToolStripMenuItem delMenuItem = new ToolStripMenuItem();
            delMenuItem.Text = "删除";
            delMenuItem.Click += deleteWaittingImportMedia_Click;
            mediaNameColumnMenu.Items.Add(delMenuItem);
        }

        private void ImportForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //如果正在编码则停止编码
            if (iboolTaskEndMonitor)
            {
                iEnc.StopEncoder();
            }
            ucVtrCtrMedia.playCtrl(false);
        }

        private void deleteWaittingImportMedia_Click(object sender, EventArgs e)
        {
            if (delRowIndex != -1)
            {
                long mediaPackID = (long)dgvMediaPack.Rows[delRowIndex].Cells[5].Value;
                if (dicTaskMediaPack.ContainsKey(mediaPackID) == true)
                    dicTaskMediaPack.Remove(mediaPackID);
                if (waitingBurnMediaPackList.Contains(mediaPackID) == true)
                    waitingBurnMediaPackList.Remove(mediaPackID);
                dgvMediaPack.Rows.Remove(dgvMediaPack.Rows[delRowIndex]);
                delRowIndex = -1;
            }
            
        }

        private void dgvMediaPack_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (dgvMediaPack.Rows[e.RowIndex].Cells[4].Value.ToString() == "等待")
                {
                    this.delRowIndex = e.RowIndex;
                    dgvMediaPack.Rows[e.RowIndex].Cells[1].ContextMenuStrip.Show(Cursor.Position);
                }
            }
            else if(e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                object mediaPackID = dgvMediaPack.Rows[e.RowIndex].Cells[5].Value;
                if(mediaPackID != null && mediaPackID.ToString() != lblMediaPackID.Text)
                {
                    lblMediaPackID.Text = mediaPackID.ToString();
                    ClearMetaDataValue();
                    using (CCTV6Entities db = new CCTV6Entities())
                    {
                        var mediaPack = db.MediaPacks.Where(item => item.ID == (long)mediaPackID).SingleOrDefault();
                        if (mediaPack != null)
                        {
                            txtMovieName.Text = mediaPack.Name;
                            foreach (var metaData in mediaPack.MetaDataRecords)
                            {
                                foreach (Control metaDataControl in pnlMetaData.Controls)
                                {
                                    //TextBox txtMetaData = metaDataControl as TextBox;
                                    if (metaDataControl.GetType() == typeof(Label))
                                        continue;
                                    int metaDataID = int.Parse(metaDataControl.Name.Replace("txt", ""));
                                    if (metaDataID == metaData.MetaDataID)
                                    {
                                        if (metaDataControl.GetType() == typeof(TextBox))
                                        {
                                            TextBox txtMetaData = metaDataControl as TextBox;
                                            metaDataControl.Text = metaData.MetaDataContent;
                                        }
                                        else if (metaDataControl.GetType() == typeof(DateTimePicker))
                                        {
                                            DateTimePicker dMetaData = metaDataControl as DateTimePicker;
                                            dMetaData.Value = Convert.ToDateTime(metaData.MetaDataContent);
                                        }
                                        else if(metaDataControl.GetType() == typeof(ComboBox))
                                            (metaDataControl as ComboBox).SelectedItem = metaData.MetaDataContent;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void lblButton_Click(object sender, EventArgs e)
        {
            Label currentLbl = sender as Label;
            if (currentLbl != null)
            {
                switch (currentLbl.Name)
                {
                    case "lblAddMediaPack":
                        AddMediaPack();
                        break;
                    case "lblAddMetaData":
                        ClearMetaDataValue();
                        break;
                    case "lblBurnPrimary":
                        if (dicDiscDrive[cmbCDRomPrimary.Text] == Common.DiscState.Burning)
                            MessageBox.Show("该光驱正在使用中，请选择其它光驱或者稍后再试。", BaseForm.MessageBoxCaption);
                        else
                        {
                            if (BurnHelper.SetDriver(cmbCDRomPrimary.Text) == Common.DiscState.LoadDiscSuccessful)
                            {
                                BurnFiles(this.discBarcode, cmbCDRomPrimary.Text, new Dictionary<string, string> { { this.currentBurnFile, @"test\1234.mpg" } }, new DiscState(), pbFirst.Name);
                            }
                        }
                        break;
                    case "lblBurnSecondary":
                        if (dicDiscDrive[cmbCDRomSecondary.Text] == Common.DiscState.Burning)
                            MessageBox.Show("该光驱正在使用中，请选择其它光驱或者稍后再试。", BaseForm.MessageBoxCaption);
                        else
                        {
                            if (BurnHelper.SetDriver(cmbCDRomSecondary.Text) == Common.DiscState.LoadDiscSuccessful)
                            {
                                if (BurnHelper.SetDriver(cmbCDRomSecondary.Text) == Common.DiscState.LoadDiscSuccessful)
                                {
                                    BurnFiles(this.discBarcode, cmbCDRomSecondary.Text, new Dictionary<string, string> { { this.currentBurnFile, @"test\1234.mpg" } }, new DiscState(), pbSecond.Name);
                                }
                            }
                        }
                        break;
                }
            }
        }

        private void lblButton_MouseMove(object sender, MouseEventArgs e)
        {
            Label currentLbl = sender as Label;
            if (currentLbl != null)
            {
                switch (currentLbl.Name)
                {
                    case "lblAddMediaPack":
                        lblAddMediaPack.Image = global::MediaClient.Properties.Resources.保存按钮_1;
                        break;
                    case "lblAddMetaData":
                        lblAddMetaData.Image = global::MediaClient.Properties.Resources.新增按钮_1;
                        break;
                    case "lblBurnPrimary":
                        lblBurnPrimary.Image = global::MediaClient.Properties.Resources.刻录_1;
                        break;
                    case "lblBurnSecondary":
                        lblBurnSecondary.Image = global::MediaClient.Properties.Resources.刻录_1;
                        break;
                }
            }
        }

        private void lblButton_MouseLeave(object sender, EventArgs e)
        {
            Label currentLbl = sender as Label;
            if (currentLbl != null)
            {
                switch (currentLbl.Name)
                {
                    case "lblAddMediaPack":
                        lblAddMediaPack.Image = global::MediaClient.Properties.Resources.保存按钮;
                        break;
                    case "lblAddMetaData":
                        lblAddMetaData.Image = global::MediaClient.Properties.Resources.新增按钮;
                        break;
                    case "lblBurnPrimary":
                        lblBurnPrimary.Image = global::MediaClient.Properties.Resources.刻录;
                        break;
                    case "lblBurnSecondary":
                        lblBurnSecondary.Image = global::MediaClient.Properties.Resources.刻录;
                        break;
                }
            }
        }

        private void ucVtrCtrMediaMarkIn_Clik(object sender, EventArgs e)
        {
        }

        private void ucVtrCtrMediaMarkInValue_DoubleClick(object sender, EventArgs e)
        {
            //if (dgv_Recing.Rows.Count > 0)
            //{
            //    if (checkMarkTime(ucVtrCtrMain.labelStartTD.Text, ucVtrCtrMain.labelEndTD.Text))
            //    {

            //        DataRowView drv = (DataRowView)localMediaPackSetBindingSource.Current;
            //        drv["Col_MarkIn"] = ucVtrCtrMain.labelStartTD.Text;
            //        drv.EndEdit();
            //    }

            //}
        }

        private void ucVtrCtrMediaMarkOutValue_DoubleClick(object sender, EventArgs e)
        {
            string lsStd = ucVtrCtrMedia.labelStartTD.Text;
            string lsEtd = ucVtrCtrMedia.labelEndTD.Text;

            long lStd = Of_CtrFrameByTimecode(lsStd);
            long lEtd = Of_CtrFrameByTimecode(lsEtd);
            if (lStd >= lEtd)
            {
                MessageBox.Show("时间码错误！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //COper.of_Log("时间码错误！", this);
                return;
            }
            long llen = lEtd - lStd;
            if (llen <= 50)//长度不够
            {
                //COper.of_Log("时间长度错误，必须大于2秒！", this);
                MessageBox.Show("时间长度必须大于2秒！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void ucVtrCtrMedia_oeCVtrbtnMarkOut(string lsStd, string lsEtd, int liTDMode)
        {

        }

        private void ucVtrCtrMedia_oeCVtrbtnARec(bool lboolARecState)
        {
            //if (JudgeDisc() == false)
            //    return;
            ///创建目录
            if (!Directory.Exists(isClipsDir))
            {
                Directory.CreateDirectory(isClipsDir);
            }

            //MessageBox.Show("11");
            try
            {
                if (HaveImportingTask() == false)
                {
                    MessageBox.Show("请先添加录制的任务。", BaseForm.MessageBoxCaption);
                    return;
                }

                if (ucVtrCtrMedia.iboolVTRConState == false)
                {
                    MessageBox.Show("警告：未连接到录像机，无法自动采集！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //COper.of_Log("警告：未连接到录像机，无法自动采集！", this);
                    return;
                }

                //开始编码
                if (!lboolARecState)
                {
                    #region 将要采集的 数据集合加入到数组中

                    

                    #endregion
                    //MessageBox.Show(isFrameCount);
                    Of_StartTaskList();
                }
                //停止编码
                else
                {
                    //MessageBox.Show(isFrameCount);
                    Of_StopTaskList();
                }
            }
            catch (Exception ex)
            { 
                //COper.of_Log(ex.Message + ex.StackTrace, this);
            }
        }

        private void ucVtrCtrMedia_oeCVtrbtnMRec(bool lboolMRecState)
        {
            //if (JudgeDisc() == false)
            //    return;
            if (HaveImportingTask() == false)
            {
                MessageBox.Show("请先添加录制的任务。", BaseForm.MessageBoxCaption);
                return;
            }
            if (Directory.Exists(isClipsDir) == false)
                Directory.CreateDirectory(isClipsDir);
            if (isRecStart == false)
            {
                string captureFileName = isClipsDir + "\\" + txtMovieName.Text.Trim() + "_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
                isHFileC = captureFileName + captureConfig.VideoExtension;
                string audioFile = "";
                string lowFile = captureFileName + BaseForm.lowFileExtension.Trim();

                isMSTC = ucVtrCtrMedia.isCurrentTD;
                ucVtrCtrMedia.iboolMRecState = true;
                ucVtrCtrMedia.iboolARecState = false;
                if (isMSTC.Length != 11)
                {
                    UCVtrCtr.VTRCTLReset(ucVtrCtrMedia.iHandle);
                    UCVtrCtr.VTRCTLReset(ucVtrCtrMedia.iHandle);
                    UCVtrCtr.VTRCTLReset(ucVtrCtrMedia.iHandle);
                    isMSTC = ucVtrCtrMedia.isCurrentTD;
                }
                ucVtrCtrMedia.playCtrl(true);
                isRecStart = true;


                int res;
                res = encoder.StartCapture(isHFileC, audioFile, lowFile);
                //MessageBox.Show(res.ToString());
                if (res != 1)
                {
                    MessageBox.Show("设置编码参数的时候发生错误！", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    isRecStart = false;
                    return;
                }

                currRecRow = dicTaskMediaPack.Count() == 0? dgvMediaPack.Rows[0]: GetDataRowByMediaPackID(dicTaskMediaPack.Keys.First().ToString());
                currRecRow.Cells[4].Value = "进行中";
                markIn = currRecRow.Cells[6].Value.ToString();
                markOut = currRecRow.Cells[7].Value.ToString();
                //labelState.Text = "正在采集";
                ucVtrCtrMedia.btnEnable(false);

                //设置标志位
                ucVtrCtrMedia.iboolMRecState = true;

                string[] mediaPackFiles = Directory.GetFiles(this.isClipsDir, Path.GetFileNameWithoutExtension(captureFileName) + ".*");
                foreach (var mediaFile in mediaPackFiles)
                {
                    if (Path.GetExtension(mediaFile).ToLower() != BaseForm.lowFileExtension.Trim())
                    {
                        lock (burnObjectLock)
                        {
                            if (dicMediaPackFile.ContainsKey(txtMovieName.Text.Trim()) == false)
                                dicMediaPackFile.Add(txtMovieName.Text.Trim(), new List<string>());
                            dicMediaPackFile[txtMovieName.Text.Trim()].Add(mediaFile);
                        }
                    }
                }
                Thread.Sleep(500);
                burnTimer.Start();
                //SetBurningMediaPack(txtMovieName.Text.Trim(), ucVtrCtrMedia.labelStartTD.Text.Trim(), ucVtrCtrMedia.labelEndTD.Text.Trim());
            }
            else
            {
                #region 停止编码
                ucVtrCtrMedia.btnEnable(true);
                isRecStart = false;
                burnTimer.Stop();
                encoder.StopCapture();
                ucVtrCtrMedia.playCtrl(false); //控制录像机播放

                #endregion

                //设置标志位
                ucVtrCtrMedia.iboolMRecState = false;
            }
        }

        private void ucVtrCtrMedia_oeCVtrbtnPreView(bool lboolPviewState)
        {
            
            if (!lboolPviewState)
            {
                iEnc.SetPreview(true);
                ucVtrCtrMedia.iboolPViewState = true;
            }
            else
            {
                iEnc.SetPreview(false);
                ucVtrCtrMedia.iboolPViewState = false;
            }
        }

        private void dgvMediaPack_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            dgvMediaPack.ClearSelection();
            dgvMediaPack.Columns[e.ColumnIndex].Selected = false;
        }

        private void ucVtrCtrMedia_ReachMarkOut(string markOutValue)
        {
            //lock (dicTaskMediaPack)
            //{
            //    foreach (var mediaPackID in dicTaskMediaPack.Keys)
            //    {
            //        if (dicTaskMediaPack[mediaPackID].Key == markOutValue)
            //        {
            //            dicTaskMediaPack.Remove(mediaPackID);
            //            foreach (DataGridViewRow dataRow in dgvMediaPack.Rows)
            //            {
            //                //if(dataRow.
            //            }
            //        }
            //    }
            //}

            if (isRecStart == true)
            {
                encoder.StopCapture();
            }
            ucVtrCtrMedia.btnEnable(true);
            ucVtrCtrMedia.playCtrl(false);
            ucVtrCtrMedia.iboolMRecState = true; ;
        }

        private void importTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (HaveImportingTask() == false) return;
                if (isRecStart == true || isSeeking == true) return;
                if (isTaskRuning == true)
                {
                    if (isTaskCue == true)
                    {
                        string lsTD = "";
                        lsTD = UCVtrCtr.VTRGetTimeCode_S(ucVtrCtrMedia.iHandle); //取当前的时码
                        if (lsTD == cueTime)
                        {
                            System.Threading.Thread.Sleep(700);
                            //cue操作结束
                            isTaskCue = false;
                            canStartRec = true;
                            //COper.of_Log("VTRPlay。", this);
                            UCVtrCtr.VTRPlay(ucVtrCtrMedia.iHandle); //开始播放
                            isSeeking = true;
                        }
                        return;
                    }
                    importTimer.Stop();

                    if (HaveImportingTask() == false && currRecRow == null) //队列中没有任务数据，停止任务监控
                    {
                        ucVtrCtrMedia.iboolARecState = false;
                        //如果完成的任务和任务列表数量一致，结束编码
                        //停止编码
                        //COper.of_Log("停止批采功能", this);
                        //设置标志位
                        ucVtrCtrMedia.iboolARecState = false;

                        //停止时钟
                        importTimer.Stop();
                        //设置自动批量采集ucVtrCtrMain控件属性
                        ucVtrCtrMedia.of_SetARecCtrState();
                        //设置FormMain窗口控件表现
                        


                        //关闭任务列表监听
                        isTaskRuning = false;
                        //COper.of_Log("自动采集任务全部结束。", this);
                        
                        dgvMediaPack.Refresh();
                        return;
                    }
                    
                    currRecRow = dicTaskMediaPack.Count() == 0 ? dgvMediaPack.Rows[0] : GetDataRowByMediaPackID(dicTaskMediaPack.Keys.First().ToString());
                    currRecRow.Cells[4].Value = "进行中";
                    markIn = currRecRow.Cells[6].Value.ToString();
                    markOut = currRecRow.Cells[7].Value.ToString();
                    dicTaskMediaPack.Remove(dicTaskMediaPack.Keys.First());
                    //if (lsTdMode == "TC")
                    //{ iiTdMode = 0; }
                    //else if (lsTdMode == "CTL")
                    //{ iiTdMode = 1; }

                    isMSTC = ucVtrCtrMedia.isCurrentTD;


                    //设置时间模式
                    UCVtrCtr.VTRSetTcMode(ucVtrCtrMedia.iHandle, iiTdMode);
                    UCVtrCtr.VTRSetTcMode(ucVtrCtrMedia.iHandle, iiTdMode);
                    UCVtrCtr.VTRSetTcMode(ucVtrCtrMedia.iHandle, iiTdMode);
                    ucVtrCtrMedia.buttonVtrTDMode.Text = iiTdMode == 0 ? "TC" : "CTL";
                    ucVtrCtrMedia.iTdMode = iiTdMode;

                    //预卷

                    CalPreTime(markIn, ref cueTime);

                    //COper.of_Log("cue:" + cueTime, this);

                    UCVtrCtr.VTRCue_S(ucVtrCtrMedia.iHandle, cueTime);//Cue Enc


                    //开始Cue监听
                    iiTaskCueCount = 0;
                    isTaskCue = true;

                    importTimer.Start();//重启任务监听
                }
            }
            catch (Exception myE)
            {
            }
        }

        private void burnTimer_Tick(object sender, EventArgs e)
        {
            if (isBurning == false)
            {
                lock (burnObjectLock)
                {
                    if (waitingBurnMediaPackList.Count() == 0)
                        return;
                }
                pnlPrimaryInfo.Visible = true;
                pnlSecond.Visible = true;
                isBurning = true;
                List<string> mediaPackFileList = null;
                string mediaPackName = null;
                mediaPackName = GetDataRowByMediaPackID(waitingBurnMediaPackList[0].ToString()).Cells[1].Value.ToString();
                mediaPackFileList = dicMediaPackFile[mediaPackName];

                lblBurnNameFirst.Text = mediaPackName;
                //GetBurningMediaPackInfo(mediaPackName, mediaPackFileList);
                pbFirst.Maximum = 100;
                string burnFullPath = Path.Combine(mediaPackName, this.burnPath);
                Dictionary<string, string> burningMediaPackFile = new Dictionary<string, string>();
                using (CCTV6Entities db = new CCTV6Entities())
                {
                    try
                    {
                        mediaPackFileList.ForEach(mediaFile =>
                        {
                            string fileName = "clip_";
                            string fileExtension = Path.GetExtension(mediaFile);
                            string[] fileNameArray = Path.GetFileNameWithoutExtension(mediaFile).Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                            if (Regex.IsMatch(fileNameArray[fileNameArray.Length - 1], @"\d+") == true)
                                fileName += fileNameArray[fileNameArray.Length - 1] + fileExtension;
                            else
                                fileName += fileExtension;
                            string burnFile = Path.Combine(burnFullPath, fileName);
                            FileInfo mediaFileInfo = new FileInfo(mediaFile);
                            burningMediaPackFile.Add(mediaFile, burnFile);
                            DiscFile oDiscFile = new DiscFile { DiscBarcode = this.discBarcode, CreateDate = DateTime.Now, Extension = fileExtension, MediaPackID = waitingBurnMediaPackList[0], Name = Path.GetFileName(burnFile), Path = Path.GetDirectoryName(burnFile), Size = mediaFileInfo.Length };
                            db.DiscFiles.AddObject(oDiscFile);
                        });
                        db.SaveChanges();
                    }
                    finally
                    {
                    }
                }

                lock (burnDiscDriveLock)
                {
                    int i = 1;
                    foreach (var discDriveName in this.dicDiscDrive.Keys)
                    {
                        if (discDriveName.Contains("G:") == true)
                        {
                            if (dicDiscDrive[discDriveName] == DiscState.LoadDiscSuccessful || dicDiscDrive[discDriveName] == DiscState.BurnSuccessful)
                            {
                                DiscState burningDiscState = dicDiscDrive[discDriveName];
                                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
                                {
                                    if (i == 1)
                                        BurnHelper.SynchronizationBurnData(this.discBarcode, 2, discDriveName, burningMediaPackFile, ref burningDiscState, ref discRemainCapacity, false, pbFirst.Name);
                                }));
                                break;
                                dicDiscDrive[discDriveName] = burningDiscState;
                            }
                        }
   
                    }
                }
            }
        }

        private void WatchTaskTimer_Tick(object sender, EventArgs e)
        {
            if (isTaskRuning && currRecRow != null && canStartRec)
            {
                if (isTaskCue) return;

                string lsTD = "";
                lsTD = UCVtrCtr.VTRGetTimeCode_S(ucVtrCtrMedia.iHandle);

                if(Math.Abs(TimeStringToFrame(lsTD)-TimeStringToFrame(markIn)) <= 12)
                {
                    isSeeking = false;
                    //开始编码
                    isRecStart = true;
                    int res = 0;
                    //if (isBurning == false)
                    {
                        
                        string fileName = currRecRow.Cells[1].Value.ToString();
                        string captureFileName = isClipsDir + "\\" + fileName + "_" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        captureFileName += captureConfig.VideoExtension;
                        string audioFile = "";
                        string lowFile = captureFileName + BaseForm.lowFileExtension.Trim();
                        currRecRow.Cells[4].Value = "进行中";
                        markIn = currRecRow.Cells[6].Value.ToString();
                        markOut = currRecRow.Cells[7].Value.ToString();
                        res = encoder.StartCapture(captureFileName, audioFile, lowFile);
                        
                        string[] mediaPackFiles = Directory.GetFiles(this.isClipsDir, Path.GetFileNameWithoutExtension(captureFileName) + ".*");
                        foreach (var mediaFile in mediaPackFiles)
                        {
                            if (Path.GetExtension(mediaFile).ToLower() != BaseForm.lowFileExtension.Trim())
                            {
                                lock (burnObjectLock)
                                {
                                    if (dicMediaPackFile.ContainsKey(fileName) == false)
                                        dicMediaPackFile.Add(fileName, new List<string>());
                                    dicMediaPackFile[fileName].Add(mediaFile);
                                }
                            }
                        }
                        Thread.Sleep(100);
                        burnTimer.Start();
                    }
                    //res = encoder.StartCapture("", "", "");
                    if (res != 1)
                    {
                        isRecStart = false;
                        return;
                    }
                }
            }

            if (isRecStart)
            {
                if (isTaskRuning && currRecRow != null)
                {
                    string lsTD = "";
                    lsTD = UCVtrCtr.VTRGetTimeCode_S(ucVtrCtrMedia.iHandle);
                    if(TimeStringToFrame(lsTD) >= TimeStringToFrame(markOut))
                    {
                        
                        isRecStart = false;

                        //int uFramNum1 = 0;
                        //encoder.GetFrameCount(ref uFramNum1);
                        encoder.StopCapture();
                        burnTimer.Stop();
                        currRecRow.Cells[4].Value = "完成";
                        ucVtrCtrMedia.playCtrl(false);
                        if (isBurning == false)
                        {
                            importTimer.Start();
                            ucVtrCtrMedia.btnEnable(true);
                        }
                    }
                }
            }
        }

        private void lblClose_Click(object sender, EventArgs e)
        {
            bool flag = true;
            if (waitingBurnMediaPackList.Count() >0 )
            {
                if (MessageBox.Show("还有光盘在刻录，您确定要退出吗？", BaseForm.MessageBoxCaption, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    encoder.StopCapture();
                    ucVtrCtrMedia.playCtrl(false);
                }
                else
                    flag = false;
            }
            if (flag == true)
            {
                this.Close();
            }
        }

        private void burningMediaPack_Complete(string discDriveName,string progressBarName)
        {
            try
            {
                //dicTaskMediaPack.Remove(dicTaskMediaPack.Keys.First());
                if (progressBarName == pbFirst.Name)
                {
                    if (lblCurrBurnFirst.InvokeRequired == true)
                    {
                        lblCurrBurnFirst.Invoke(new WaitCallback(delegate(object state)
                        {
                            lblCurrBurnFirst.Text = "当前刻录 " + GetBurningMediaPackLength().ToString();
                            lblLeftTimeFirst.Text = "剩余时间 00:00:00";
                            lblLeftSpaceFirst.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity);
                            pbFirst.Value = 100;
                        }), "");

                    }
                    else
                    {
                        lblCurrBurnFirst.Text = "当前刻录 " + GetBurningMediaPackLength().ToString("HH:mm:ss");
                        lblLeftTimeFirst.Text = "剩余时间 00:00:00";
                        lblLeftSpaceFirst.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity);
                        pbFirst.Value = 100;
                    }
                    if (pbSecond.Value == 100)
                    {
                        waitingBurnMediaPackList.RemoveAt(0);
                        isBurning = false;
                    }
                }
                else
                {
                    if (lblCurrBurnSecond.InvokeRequired == true)
                    {
                        lblCurrBurnSecond.Invoke(new WaitCallback(delegate(object state)
                        {
                            lblCurrBurnSecond.Text = "当前刻录 " + GetBurningMediaPackLength().ToString();
                            lblLeftTimeSecond.Text = "剩余时间 00:00:00";
                            lblLeftSpaceSecond.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity);
                            pbSecond.Value = 100;
                        }), "");

                    }
                    else
                    {
                        lblCurrBurnSecond.Text = "当前刻录 " + GetBurningMediaPackLength().ToString("HH:mm:ss");
                        lblLeftTimeSecond.Text = "剩余时间 00:00:00";
                        lblLeftSpaceSecond.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity);
                        pbSecond.Value = 100;
                    }
                    if (pbFirst.Value == 100)
                    {
                        waitingBurnMediaPackList.RemoveAt(0);
                        isBurning = false;
                    }
                }


                dicDiscDrive[discDriveName] = DiscState.BurnSuccessful;
            }
            catch
            {
            }
        }

        private void burningMediaPack_Process(string discDriveName, string progressBarName, long process)
        {
            if (progressBarName == "pbFirst")
            {
                if (lblCurrBurnFirst.InvokeRequired == true)
                {
                    lblCurrBurnFirst.Invoke(new WaitCallback(delegate(object state)
                    {
                        TimeSpan burnMediaLength = GetBurningMediaPackLength();
                        long mediaPackSize = Convert.ToInt64(this.captureConfig.VideoRate * 1024 * burnMediaLength.TotalSeconds);
                        long burnedSize = process;
                        lblLeftSpaceFirst.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity - (ulong)process / 8);
                        double burned = (double)burnedSize / mediaPackSize;
                        if (burned > 1)
                            return;

                        TimeSpan buredTime = new TimeSpan((long)(burned * burnMediaLength.TotalSeconds * 10000000));
                        TimeSpan leftTime = burnMediaLength - buredTime;
                        lblLeftTimeFirst.Text = "剩余时间 " + leftTime.Hours.ToString("00") + ":" + leftTime.Minutes.ToString("00") + ":" + leftTime.Seconds.ToString("00") + "." + leftTime.Milliseconds.ToString("####");
                        lblCurrBurnFirst.Text = "当前刻录 " + buredTime.Hours.ToString("00") + ":" + buredTime.Minutes.ToString("00") + ":" + buredTime.Seconds.ToString("00") + "." + buredTime.Milliseconds.ToString("####");
                        pbFirst.Value = (int)(burned * 100);
                    }), "");
                }
                else
                {
                    TimeSpan burnMediaLength = GetBurningMediaPackLength();
                    long mediaPackSize = Convert.ToInt64(this.captureConfig.VideoRate * 1024 * burnMediaLength.TotalSeconds);
                    long burnedSize = process;
                    lblLeftSpaceFirst.Text = "剩余空间 " + FormatDiscCapacityStr(discRemainCapacity - (ulong)process / 8);
                    double burned = (double)burnedSize / mediaPackSize;
                    if (burned > 1)
                        return;
                    TimeSpan buredTime = new TimeSpan((long)(burned * burnMediaLength.TotalSeconds * 10000000));
                    TimeSpan leftTime = burnMediaLength - buredTime;
                    lblLeftTimeFirst.Text = "剩余时间 " + leftTime.Hours.ToString("00") + ":" + leftTime.Minutes.ToString("00") + ":" + leftTime.Seconds.ToString("00") + "." + leftTime.Milliseconds.ToString("####");
                    lblCurrBurnFirst.Text = "当前刻录 " + buredTime.Hours.ToString("00") + ":" + buredTime.Minutes.ToString("00") + ":" + buredTime.Seconds.ToString("00") + "." + buredTime.Milliseconds.ToString("####");
                    pbFirst.Value = (int)(burned * 100);
                }
            }
            else
            {
                if (lblCurrBurnSecond.InvokeRequired == true)
                {
                    lblCurrBurnSecond.Invoke(new WaitCallback(delegate(object state)
                    {
                        TimeSpan burnMediaLength = GetBurningMediaPackLength();
                        long mediaPackSize = Convert.ToInt64(this.captureConfig.VideoRate * 1024 * burnMediaLength.TotalSeconds);
                        long burnedSize = process;
                        lblLeftSpaceSecond.Text = "剩余空间 " + FormatDiscCapacityStr(secondRemainCapacity - (ulong)process / 8);
                        double burned = (double)burnedSize / mediaPackSize;
                        if (burned > 1)
                            return;

                        TimeSpan buredTime = new TimeSpan((long)(burned * burnMediaLength.TotalSeconds * 10000000));
                        TimeSpan leftTime = burnMediaLength - buredTime;
                        lblLeftTimeSecond.Text = "剩余时间 " + leftTime.Hours.ToString("00") + ":" + leftTime.Minutes.ToString("00") + ":" + leftTime.Seconds.ToString("00") + "." + leftTime.Milliseconds.ToString("####");
                        lblCurrBurnSecond.Text = "当前刻录 " + buredTime.Hours.ToString("00") + ":" + buredTime.Minutes.ToString("00") + ":" + buredTime.Seconds.ToString("00") + "." + buredTime.Milliseconds.ToString("####");
                        pbSecond.Value = (int)(burned * 100);
                    }), "");
                }
                else
                {
                    TimeSpan burnMediaLength = GetBurningMediaPackLength();
                    long mediaPackSize = Convert.ToInt64(this.captureConfig.VideoRate * 1024 * burnMediaLength.TotalSeconds);
                    long burnedSize = process;
                    lblLeftSpaceSecond.Text = "剩余空间 " + FormatDiscCapacityStr(secondRemainCapacity - (ulong)process / 8);
                    double burned = (double)burnedSize / mediaPackSize;
                    if (burned > 1)
                        return;

                    TimeSpan buredTime = new TimeSpan((long)(burned * burnMediaLength.TotalSeconds * 10000000));
                    TimeSpan leftTime = burnMediaLength - buredTime;
                    lblLeftTimeSecond.Text = "剩余时间 " + leftTime.Hours.ToString("00") + ":" + leftTime.Minutes.ToString("00") + ":" + leftTime.Seconds.ToString("00") + "." + leftTime.Milliseconds.ToString("####");
                    lblCurrBurnSecond.Text = "当前刻录 " + buredTime.Hours.ToString("00") + ":" + buredTime.Minutes.ToString("00") + ":" + buredTime.Seconds.ToString("00") + "." + buredTime.Milliseconds.ToString("####");
                    pbSecond.Value = (int)(burned * 100);
                }
            }
            
        }

        #endregion

        #region private methods

        private void AddMetaDataControl()
        {
            pnlMetaData.Controls.Clear();
            using (CCTV6Entities db = new CCTV6Entities())
            {
                currentY = 10 + 38 * index;
                foreach (var metaData in db.MetaDataNames.OrderBy(metadata => metadata.ID))
                {
                    
                    Label lblCatalogMeta = new Label();
                    lblCatalogMeta.Width = lblMovieName.Width;
                    lblCatalogMeta.TextAlign = ContentAlignment.MiddleRight;
                    lblCatalogMeta.Text = metaData.Name;
                    lblCatalogMeta.AutoSize = false;
                    lblCatalogMeta.Height = lblMovieName.Height;
                    lblCatalogMeta.ForeColor = lblMovieName.ForeColor;
                    lblCatalogMeta.Font = lblMovieName.Font;
                    lblCatalogMeta.Location = new Point(0, currentY);
                    
                    this.pnlMetaData.Controls.Add(lblCatalogMeta);

                    Control metaDataControl = null;
                    
                    switch (metaData.DataType)
                    {

                        case 2:  //多行文本框
                            TextBox txtMuti = new TextBox();
                            txtMuti.Multiline = true;
                            txtMuti.Height = txtMovieName.Height;
                            txtMuti.Location = new Point(112, currentY-2);
                            txtMuti.Width = txtMovieName.Width;
                            txtMuti.ScrollBars = ScrollBars.Vertical;
                            txtMuti.Height = txtMovieName.Height * 4;
                            metaDataControl = txtMuti;
                            index++;
                            currentY += 102;
                            break;
                        case 1: //单行文本框
                            metaDataControl = new TextBox();
                            metaDataControl.Width = txtMovieName.Width;
                            metaDataControl.Location = new Point(112, currentY - 2);
                            currentY += 38;
                            break;
                        case 3: //时间空间
                            DateTimePicker dControl = new DateTimePicker();
                            //dControl.Value = DateTime.Parse("1999-12-04");
                            metaDataControl = dControl;
                            metaDataControl.Width = txtMovieName.Width;
                            metaDataControl.Location = new Point(112, currentY - 2);
                            currentY += 38;
                            break;
                        case 6: //下拉框
                            ComboBox cbMeta = new ComboBox();
                            cbMeta.DropDownStyle = ComboBoxStyle.DropDownList;
                            cbMeta.DataSource = metaData.MetadataValue.ValueList.Split(new char[] { ';', '；' }, StringSplitOptions.RemoveEmptyEntries);
                            if (cbMeta.Items.Count > 0)
                                cbMeta.SelectedIndex = 0;
                            metaDataControl = cbMeta;
                            metaDataControl.Width = txtMovieName.Width;
                            metaDataControl.Location = new Point(112, currentY - 2);
                            currentY += 38;
                            break;
                        default:
                            //metaDataControl 
                            break;
                    }
                    metaDataControl.Name = "txt" + metaData.ID;
                    if (metaDataControl != null)
                        pnlMetaData.Controls.Add(metaDataControl);
                    index++;
                }
            }



        }

        private void ClearMetaDataValue()
        {
            txtMovieName.Text = "";
            txtMovieName.Focus();
            lblMediaPackID.Text = "";
            foreach (Control metaDataControl in pnlMetaData.Controls)
            {
                if (metaDataControl.GetType() == typeof(TextBox))
                    (metaDataControl as TextBox).Text = "";
                else if (metaDataControl.GetType() == typeof(DateTimePicker))
                    (metaDataControl as DateTimePicker).Value = DateTime.Now;
                else if (metaDataControl.GetType() == typeof(ComboBox))
                    (metaDataControl as ComboBox).SelectedIndex = 0;
                
            }
        }

        private void AddMediaPack()
        {
            bool addMedia = true;
            foreach (long mediaPackID in dicTaskMediaPack.Keys)
            {
                
                if (lblMediaPackID.Text != mediaPackID.ToString() && dicTaskMediaPack[mediaPackID].Key == ucVtrCtrMedia.labelStartTD.Text && dicTaskMediaPack[mediaPackID].Value == ucVtrCtrMedia.labelEndTD.Text)
                {
                    MessageBox.Show("已有相同的采集任务。", BaseForm.MessageBoxCaption);
                    return;
                }
            }

            if (TimeStringToFrame(ucVtrCtrMedia.labelEndTD.Text.Trim()) <= TimeStringToFrame(ucVtrCtrMedia.labelStartTD.Text.Trim()))
            {
                MessageBox.Show("任务的结束点不可以小于起始点。", BaseForm.MessageBoxCaption);
                return;
            }
            TimeSpan mediaPackLength = new TimeSpan();
            if (lblMediaPackID.Text == "")
            {
                mediaPackLength = (GetTimeSpan(ucVtrCtrMedia.labelEndTD.Text.Trim()) - GetTimeSpan(ucVtrCtrMedia.labelStartTD.Text.Trim()));
                ulong mediaPackSize = Convert.ToUInt64(captureConfig.VideoRate * mediaPackLength.TotalSeconds / 8);
                sumTaskMediaPackSize += mediaPackSize;
                if (sumTaskMediaPackSize >= captureConfig.DiscCapacity)
                {
                    MessageBox.Show("包括该任务，总任务的数据大小已超过所选的盘片大小,请换盘片。", BaseForm.MessageBoxCaption);
                    return;
                }

                
            }
            if (this.txtMovieName.Text.Trim() == "")
            {
                MessageBox.Show("请输入素材名称。",BaseForm.MessageBoxCaption);
                this.txtMovieName.Focus();
                return;
            }

            using (CCTV6Entities db = new CCTV6Entities())
            {
                
                MediaPack oMediaPack = null;
                if (lblMediaPackID.Text != "")
                    oMediaPack = db.MediaPacks.SingleOrDefault(media => media.ID == long.Parse(lblMediaPackID.Text));
                if (oMediaPack == null)
                    oMediaPack = new MediaPack();
                else
                    addMedia = false;
                oMediaPack.Name = txtMovieName.Text.Trim();
                oMediaPack.DiscBarcode = this.discBarcode;
                oMediaPack.SourceType = this.sourceType;
                oMediaPack.UserID = loginUser == null ? "admin" : loginUser.ID;
                oMediaPack.CodeRate = this.codeRate;
                oMediaPack.CreateDate = DateTime.Now;
                oMediaPack.Length = mediaPackLength;
                if (oMediaPack.ID == 0) //新增数据
                    db.MediaPacks.AddObject(oMediaPack);
                else //删除元数据项
                {
                    foreach (var metaData in oMediaPack.MetaDataRecords)
                        db.MetaDataRecords.DeleteObject(metaData);
                }
                db.SaveChanges();
                lblMediaPackID.Text = oMediaPack.ID.ToString();
                foreach (var metaDataControl in pnlMetaData.Controls)
                {
                    Type metaDataControlType = metaDataControl.GetType();
                    string metaDataID = (metaDataControl as Control).Name.Replace("txt", string.Empty);
                    if (Regex.IsMatch(metaDataID, @"\d+") == true)
                    {
                        MetaDataRecord oMetaDataRecord = new MetaDataRecord();
                        oMetaDataRecord.MediaPackID = oMediaPack.ID;
                        oMetaDataRecord.MetaDataID = int.Parse(metaDataID);

                        if (metaDataControlType == typeof(TextBox))
                            oMetaDataRecord.MetaDataContent = (metaDataControl as TextBox).Text.Trim();
                        else if (metaDataControlType == typeof(ComboBox))
                            oMetaDataRecord.MetaDataContent = (metaDataControl as ComboBox).SelectedItem.ToString();
                        else if (metaDataControlType == typeof(DateTimePicker))
                            oMetaDataRecord.MetaDataContent = (metaDataControl as DateTimePicker).Value.ToString("yyyy-MM-dd");
                        if (oMetaDataRecord.MetaDataContent.Trim() != string.Empty)
                        {
                            db.MetaDataRecords.AddObject(oMetaDataRecord);
                            db.SaveChanges();
                        }
                    }
                }
                if (addMedia)
                {
                    DataGridViewRow mediaPackDataRow = new DataGridViewRow();
                    mediaPackDataRow.CreateCells(dgvMediaPack);
                    mediaPackDataRow.Cells[1].Value = txtMovieName.Text.Trim();
                    mediaPackDataRow.Cells[2].Value = GetCodeRateStr(this.captureConfig.VideoRate);
                    mediaPackDataRow.Cells[3].Value = mediaPackLength;
                    mediaPackDataRow.Cells[4].Value = "等待";
                    mediaPackDataRow.Cells[5].Value = oMediaPack.ID;
                    mediaPackDataRow.Cells[6].Value = ucVtrCtrMedia.labelStartTD.Text;
                    mediaPackDataRow.Cells[7].Value = ucVtrCtrMedia.labelEndTD.Text;
                    dgvMediaPack.Rows.Add(mediaPackDataRow);
                    mediaPackDataRow.Cells[1].ContextMenuStrip = this.mediaNameColumnMenu;
                    lblMediaPackID.Text = "";
                    dicTaskMediaPack.Add(oMediaPack.ID, new KeyValuePair<string, string>(ucVtrCtrMedia.labelStartTD.Text, ucVtrCtrMedia.labelEndTD.Text));
                    waitingBurnMediaPackList.Add(oMediaPack.ID);
                }
            }
            
        }

        private string GetCodeRateStr(int codeRate)
        {
            int result = codeRate/1000;
            if(result >=1)
                return string.Format("{0}Mbps",result);
            else 
                return string.Format("{0}Kbps",result);
        }

        private TimeSpan GetTimeSpan(string sourceStr)
        {
            TimeSpan tempTime = new TimeSpan(0,0,0,0,0);
            string[] timeArray = sourceStr.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            try
            {
                tempTime = new TimeSpan(0, int.Parse(timeArray[0]), int.Parse(timeArray[1]), int.Parse(timeArray[2]), Convert.ToInt32(float.Parse(timeArray[3]) / 25) * 1000);
            }
            catch
            {
            }
            return tempTime;
        }

        private void ConnectVTR()
        {
            try
            {
                encoder = FlexEncoder.CreateInstance();
                int res = encoder.SetFlexInfo(this.pnlMediaShow.Handle);
            }
            catch
            {
            }
        }

        /// <summary>
        /// 时间码转化为帧数 00:00:00:00
        /// </summary>
        /// <param name="timeString">时间码</param>
        /// <returns>帧数</returns>
        private long TimeStringToFrame(string timeString)
        {
            try
            {
                if (timeString.Length != 11) return -1L;
                TimeSpan sp = TimeSpan.Parse(timeString.Substring(0, 8) + ".000");
                long frames = (long)sp.TotalSeconds * 25 + Convert.ToInt64(timeString.Substring(9, 2));
                return frames;
            }
            catch
            {
                return -1;
            }

        }

        /// <summary>
        /// 帧转换成时间 
        /// </summary>
        /// <param name="frameNum">帧数</param>
        /// <returns></returns>
        private string FrameToTimeString(ulong frameNum)
        {
            ulong frameAtStringEnd = frameNum % 25; // 取时间格式 00：00：00：00的最后两位帧数
            string timeLength = TimeSpan.FromSeconds(frameNum / 25).ToString();
            timeLength = timeLength + ":" + frameAtStringEnd.ToString("00");
            return timeLength;

        }

        /// <summary>
        /// 计算预卷时间
        /// </summary>
        /// <param name="oldTime">原始时间</param>
        /// <param name="newTime">新时间时间</param>
        /// <returns></returns>
        bool CalPreTime(string oldTime, ref string newTime)
        {
            newTime = oldTime;
            try
            {
                long frameNum = TimeStringToFrame(oldTime);
                frameNum = frameNum - Properties.Settings.Default.preCueSecs * 25;
                newTime = FrameToTimeString((ulong)frameNum);
                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 根据输入的时间码换算为帧数
        /// </summary>
        /// <param name="llFrame"></param>
        /// <returns></returns>
        public long Of_CtrFrameByTimecode(string lsTimecode)
        {
            try
            {
                long ll_frameNo = 0;
                if (lsTimecode.Length < 11) return -1;
                double lFramePerSec = 25;//Math.Ceiling(iFramePerSec);
                long llH = long.Parse(lsTimecode.Substring(0, 2));
                long llm = long.Parse(lsTimecode.Substring(3, 2));
                long lls = long.Parse(lsTimecode.Substring(6, 2));
                long llf = long.Parse(lsTimecode.Substring(9, 2));
                ll_frameNo = (3600 * llH + 60 * llm + lls) * (long)(lFramePerSec) + llf;
                return ll_frameNo;
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
            }
            return 0;
        }

        private bool HaveImportingTask()
        {
            bool haveTask = false;
            if (dgvMediaPack.Rows.Count > 0)
            {
                foreach (DataGridViewRow dataRow in dgvMediaPack.Rows)
                {
                    string taskStatus = dataRow.Cells[4].Value.ToString();
                    if (taskStatus == "等待" || taskStatus == "进行中")
                    {
                        haveTask = true;
                        break;
                    }
                }
            }
            return haveTask;
        }

        private void GetDiscBarcode()
        {
            try
            {
                ServiceProxy mediaServiceClient = new Common.ServiceProxy();
                this.discBarcode = mediaServiceClient.GetDiscBarcode();
                using (CCTV6Entities db = new CCTV6Entities())
                {
                    if (db.BlueDiscs.SingleOrDefault(disc => disc.Barcode == this.discBarcode) == null)
                    {
                        BlueDisc oDisc = new BlueDisc();
                        oDisc.Barcode = this.discBarcode;
                        oDisc.BurnCount = (short)this.captureConfig.BurnType;
                        oDisc.Capacity = (long)this.captureConfig.DiscCapacity;
                        oDisc.CreateDate = DateTime.Now.ToString("yyyyMMdd");
                        oDisc.Name = this.captureConfig.DiscName; ;
                        db.BlueDiscs.AddObject(oDisc);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception myE)
            {
            }
        }

        private void GetBurningMediaPackInfo(string buningMediaPackName,List<string> mediaPackFiles)
        {
            
            long burningMediaPackSize = 0;
            foreach (var mediaFile in mediaPackFiles)
            {
                FileInfo oFileInfo = new FileInfo(mediaFile);
                if (oFileInfo != null)
                    burningMediaPackSize += oFileInfo.Length;
            }
            this.burningMediaPackInfo = new KeyValuePair<string, long>(buningMediaPackName, burningMediaPackSize);
        }

        private void InitializeBurningDiscDrives()
        {
            this.dicDiscDrive = BurnHelper.InitAndGetDriversName();
            foreach (var key in dicDiscDrive.Keys)
            {
                cmbCDRomPrimary.Items.Add(key);
                cmbCDRomSecondary.Items.Add(key);
            }

            if (cmbCDRomPrimary.Items.Count > 0)
                cmbCDRomPrimary.SelectedIndex = 0;
            if (cmbCDRomSecondary.Items.Count > 1)
                cmbCDRomSecondary.SelectedIndex = 1;
        }

        private bool JudgeDisc()
        {
            if (BurnHelper.JudgeDisc(new Dictionary<string, ulong> { { " ", this.captureConfig.DiscCapacity } }) != 0)
                return false;
            else
                return true;
        }

        private void InitializeTimer()
        {
            this.WatchTaskTimer.Start();
            this.burnTimer.Stop();
            this.importTimer.Stop();
        }

        private string FormatDiscCapacityStr(ulong discCapacity)
        {
            
            string formateString = "0GB";
            ulong GB = 1024L*1024L*1024L;
            ulong MB = 1024L * 1024L;
            uint KB = 1024;
            if (discCapacity >= GB)
                formateString = (((double)discCapacity) / GB).ToString("#.#") + " GB";
            else if (discCapacity >= MB)
                formateString = (((double)discCapacity) / MB).ToString("#.#") + " MB";
            else if (discCapacity >= KB)
                formateString = (((double)discCapacity) / MB).ToString("#.#") + " KB";
            else
                formateString = discCapacity.ToString() + " B";

            return formateString;
        }

        private TimeSpan GetBurningMediaPackLength()
        {
            //return (GetTimeSpan(currRecRow.Cells[7].Value.ToString()) - GetTimeSpan(currRecRow.Cells[6].Value.ToString()));;
            DateTime myTime = DateTime.Now;
            return (myTime.AddMinutes(5) - myTime);
        }

        private void SetBurningMediaPack(string mediaPackName, string markIn, string markOut)
        {
            TimeSpan mediaPackLength = GetTimeSpan(markOut.Trim()) - GetTimeSpan(markIn.Trim());
            burningMediaPackInfo = new KeyValuePair<string, long>(txtMovieName.Text.Trim(), Convert.ToInt64(captureConfig.VideoRate * mediaPackLength.TotalSeconds / 8));
        }

        private DataGridViewRow GetDataRowByMediaPackID(string mediaPackID)
        {
            DataGridViewRow dataRow = null;
            foreach (DataGridViewRow item in dgvMediaPack.Rows)
            {
                if (item.Cells[5].Value.ToString() == mediaPackID)
                {
                    dataRow = item;
                    break;
                }
            }
            return dataRow;
        }

        /// <summary>
        /// 开始任务列
        /// </summary>
        private void Of_StartTaskList()
        {
            //开始编码
            //COper.of_Log("自动采集开始......", this);
            //设置标志位
            ucVtrCtrMedia.iboolARecState = true;
            //初始化
            isTaskRuning = false;
            isTaskCue = false;
            iboolTaskEndMonitor = false;
            
            //设置自动批量采集ucVtrCtrMain控件属性
            ucVtrCtrMedia.of_SetARecCtrState();
            //设置FormMain窗口控件表现
            //Of_SetfmCtrState(false);
            //打开循环编码的时钟进行循环编码
            isTaskRuning = true;
            importTimer.Start();
        }

        /// <summary>
        /// 停止任务列表
        /// </summary>
        private void Of_StopTaskList()
        {

            //停止编码
            //COper.of_Log("停止批采功能", this);
            //设置标志位
            ucVtrCtrMedia.iboolARecState = false;

            if (isRecStart) //如果是正在采集中，则要停止并关闭
            {

                #region 停止编码
                ucVtrCtrMedia.btnEnable(true);
                isRecStart = false;
                encoder.StopCapture();
                //labelState.Text = "采集完成";

                //COper.of_Log(currRecRow["name"].ToString() + "采集完成", this);
                ucVtrCtrMedia.playCtrl(false); //控制录像机播放

                #endregion

                ///状态清理
                ///
                isTaskRuning = false;
                isTaskCue = false;
                iboolTaskEndMonitor = false;
                isSeeking = false;

                //COper.of_Log("采集停止", this);
                //设置标志位
                //ucVtrCtrMain.iboolMRecState = false;
                //判断文件是否存在
                int liDBupdate = 0;
                
                if (File.Exists(isHFileC))
                {
                    FileInfo finH = new FileInfo(isHFileC);
                    if (finH.Length > 0)
                    {
                        liDBupdate = 1;
                    }
                }
            }
            

            //停止时钟
            importTimer.Stop();
            //设置自动批量采集ucVtrCtrMain控件属性
            ucVtrCtrMedia.of_SetARecCtrState();
            //设置FormMain窗口控件表现
           // Of_SetfmCtrState(true);



        }

        private void CheckDiscDrive()
        {
            if (this.captureConfig.RealTimeBurn == true)
            {
                bool IsDiscBlank = false;
                bool IsDiscWriteable = false;
                int DiscType = 0;
                foreach (var discDriveName in this.dicDiscDrive.Keys)
                {
                    BurnHelper.Rec_SetDriver(discDriveName);
                    
                    BurnHelper.Rec_GetDiscInfoEx(ref IsDiscBlank, ref IsDiscWriteable, ref DiscType, ref this.discRemainCapacity);
                }
            }
        }

        #endregion

        private void lblFileImport_Click(object sender, EventArgs e)
        {
            TransFileForm oForm = new TransFileForm();
            oForm.ShowDialog();
        }

        private void btnStartBurn_Click(object sender, EventArgs e)
        {
            this.currentBurnFile = @"D:\" + DateTime.Now.Second.ToString() + ".mpg";
            encoder.StartCapture(currentBurnFile, "", "");
        }

        private void btnStopBurn_Click(object sender, EventArgs e)
        {
            encoder.StopCapture();
        }

        private void cmbCDRom_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox burnDriver = sender as ComboBox;
            if (burnDriver != null)
            {
                if (burnDriver.Name == "cmbCDRomPrimary")
                {
                    BurnHelper.SetDriver(cmbCDRomPrimary.Text);
                }
                else if (burnDriver.Name == "")
                {
                    BurnHelper.SetDriver(cmbCDRomSecondary.Text);
                }
            }
            //BurnHelper.SetDriver(driverName);
        }

        private void BurnFiles(string discVolumName, string discDriveName, Dictionary<string, string> burnFiles, DiscState burningDiscState, string progressBarName)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
            {
                //if (i == 1)
                BurnHelper.SynchronizationBurnData(this.discBarcode, 2, discDriveName, burnFiles, ref burningDiscState, ref discRemainCapacity, false, progressBarName);
            }));
        }
        
    }
}
